package org.springframework.samples.petclinic.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.validation.ChuckOwnerValidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;


@Controller
@RequestMapping("/addOwnerChuck.do")

public class AddOwnerChuck {

	private final Clinic clinic;
	private ChuckService chuckService;

	@Autowired
	public AddOwnerChuck(Clinic clinic) {
		this.clinic = clinic;
	}	
	
	@Autowired
	public void setChuckService(ChuckService s){
		this.chuckService = s;
	}
	
    @RequestMapping(method = RequestMethod.GET)
	public String setupForm(Model model) {
		Owner owner = new Owner();
		chuckService.toConsole("hello");
		model.addAttribute(owner);
		return "ownerForm";
	}	
    
	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute Owner owner, BindingResult result, SessionStatus status) {
		new ChuckOwnerValidator().validate(owner, result);
		if (result.hasErrors()) {
			return "ownerForm";
		}
		else {
			this.chuckService.storeOwner(owner);
			status.setComplete();
			return "redirect:owner.do?ownerId=" + owner.getId();
		}
	}    
	
}
